<template>
    <div id="user-login">
        <h2>欢迎登录</h2>
        <el-form :label-position="labelPosition"  :model="user"  :rules="rules" ref="ruleForm">
            <el-form-item prop="username">
                <el-input placeholder="用户名" v-model="user.username"></el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input  type="password" placeholder="密码" v-model="user.password"></el-input>
            </el-form-item>
            <el-form-item >
                <el-button type="primary" @click="login" style="width: 100%">登录</el-button>
                <br>
                <router-link to="/register" style="color: #42b983">没有账号?点这里</router-link>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>

    import {userLogin} from "@/api/user";

    export default {
        name: "LoginView",
        data(){
            return{
                user:{
                    username:'',
                    password:''
                },
                rules: {
                    username: [
                        {required: true, message: '请输入用户名', trigger: 'blur'},
                        {min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        {min: 6, max: 8, message: '长度在 6 到 8 个字符', trigger: 'blur'}
                    ]
                },
                labelPosition:"left"
            }
        },
        methods:{
            login(){
                // TODO  将user信息提交到后台 判定用户名和密码是否正确   http://localhost:9090/user/login
                // 判定用户的数据是否符合要求
                this.$refs.ruleForm.validate(val=>{
                    if (val){
                        userLogin(this.user).then(resp=>{
                            if (resp.code==0){
                                this.$message.success(resp.message);
                                // 缓存用户登录信息到本地
                                sessionStorage.setItem("username",this.user.username)
                                //跳转路由到学生主页面
                                this.$router.push("/student")
                            }else {
                                this.$message.error(resp.message);
                            }
                        })
                    }else {
                        this.$message.warning("请填写登录信息")
                    }
                })


            }
        }
    }
</script>

<style scoped>

    #user-login{
        width: 400px;
        height: 300px;
        margin: 150px auto 0;
        text-align: center;
        color: #42b983;
    }
</style>
